package com.ksd.system.service.impl;

import com.ksd.common.weather.WeatherByAMapAPI;
import com.ksd.system.domain.SysFirst;
import com.ksd.system.service.ISysFirstService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AsynchWeatherService {
    public final Logger logger = LoggerFactory.getLogger(AsynchWeatherService.class);

    @Autowired
    private ISysFirstService sysFirstService;

    public void updateCityWeather(SysFirst sysFirst) {

        String city = sysFirst.getValue1();
        //获取最新天气
        String extensions = "all";
        WeatherByAMapAPI.fetchWeatherData(city, extensions)
                .thenApply(WeatherByAMapAPI::parseAndPrintWeather)
                .thenAccept(weatherResponse -> {
                    if (weatherResponse.getStatus().equals("1")) {
                        String dayweather = weatherResponse.getDayweather();
                        String nightweather = weatherResponse.getNightweather();
                        if (dayweather.equals(nightweather)){
                            sysFirst.setValue3(weatherResponse.getNighttemp()+"~"+weatherResponse.getDaytemp()+" "+dayweather);
                            sysFirst.setValue4("今日天气:"+dayweather+",白天温度："+weatherResponse.getDaytemp()+"℃,晚上温度："+weatherResponse.getNighttemp()+"℃");
                        }else{
                            sysFirst.setValue3(weatherResponse.getNighttemp()+"~"+weatherResponse.getDaytemp()+" "+dayweather+"转"+nightweather);
                            sysFirst.setValue4("今日天气:"+dayweather+" 转 "+nightweather+",白天温度："+weatherResponse.getDaytemp()+"℃,晚上温度："+weatherResponse.getNighttemp()+"℃");
                        }
                    } else {
                        logger.error("获取天气状态失败: " + weatherResponse.getErrorMessage());
                        sysFirst.setValue3("今日天气:获取失败");
                        sysFirst.setValue4(weatherResponse.getErrorMessage());
                    }
                    sysFirstService.updateSysFirst(sysFirst);
                    logger.info("更新天气城市:"+city+","+sysFirst.getValue2());
                })
                .exceptionally(ex -> {
                    logger.error("发生异常: " + ex.getMessage());
                    return null;
                });
    }
}
